package com.serialcommunication.communication;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.OutputStream;

public class Writer {

//	private static final int BAUT_RATE = 115200;
//	private String portName;
	private CommPort commPort;
	private OutputStream dataOutputStream;

	/**
	 * Creates Writer Object and connects to port
	 * 
	 * @param out
	 * @param pPortName
	 * @throws Exception 
	 */
	public Writer(OutputStream outputStream) {
//		portName = pPortName;
		this.dataOutputStream = outputStream;
	}

	/**
	 * writes bytes array to outputstream
	 * 
	 * @param bytes
	 * @throws Exception 
	 */
	public void write(byte[] bytes) throws Exception {
		try {
//			connect(portName);
			for (int i = 0; i < bytes.length; i++) {
				dataOutputStream.write(bytes[i]);
			}
//			dataOutputStream.close();
//			commPort.close();
			System.out.println("writing done, port and stream closed");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

//	private void connect(String pPortName) throws Exception {
//		CommPortIdentifier portIdentifier = CommPortIdentifier
//				.getPortIdentifier(pPortName);
//		if (portIdentifier.isCurrentlyOwned()) {
//			System.out.println("Error: Port is currently in use");
//		} else {
//			commPort = portIdentifier.open(this.getClass().getName(), 2000);
//			if (commPort instanceof SerialPort) {
//				SerialPort serialPort = (SerialPort) commPort;
//				serialPort.setSerialPortParams(BAUT_RATE,
//						SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
//						SerialPort.PARITY_NONE);
//
//				dataOutputStream = serialPort.getOutputStream();
//			} else {
//				System.out
//						.println("Error: Only serial ports are handled by this example.");
//			}
//		}
//	}
}
